<template>
  <div class="container">
    <div class="background-image"></div>
    <div class="content">
      <div class="view-profile">
        <el-row :gutter="20">
          <el-col :span="6" v-for="pet in pets" :key="pet.id">
            <el-card :body-style="{ padding: '20px' }" class="pet-card">
              <div>
                <p><strong>宠物名称:</strong> {{ pet.name }}</p>
                <p><strong>宠物种类:</strong> {{ pet.type }}</p>
                <p><strong>喜好:</strong> {{ pet.likes }}</p>
                <p><strong>宠物性别:</strong> {{ pet.gender }}</p>
                <p><strong>宠物出生日期:</strong> {{ formatDate(pet.birthdate) }}</p>
                <p><strong>相处细节:</strong> {{ pet.details }}</p>
              </div>
              <div class="button-container">
                <el-button class="custom-button" type="danger" @click="deletePet(pet.id)">删除</el-button>
                <el-button class="custom-button" type="primary" @click="editPet(pet)">编辑</el-button>
                <el-button class="custom-button" type="success" @click="chatWithPet(pet.id)">聊天</el-button>
                <el-button class="custom-button" type="warning" @click="viewDiary(pet.id)">日记</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import jwtDecode from 'jwt-decode';

export default {
  name: 'ViewProfile',
  data() {
    return {
      pets: [],
      userId: null
    };
  },
  created() {
    this.userId = this.getUserIdFromToken();
    this.fetchPets();
  },
  methods: {
    getUserIdFromToken() {
      const token = localStorage.getItem('token');
      if (token) {
        const decoded = jwtDecode(token);
        console.log("Decoded token:", decoded);
        const userId = decoded.userId;
        console.log("Parsed userId from token:", userId);
        return userId; // 确保 JWT 中有 userId 字段
      }
      return null;
    },
    fetchPets() {
      if (this.userId) {
        console.log(`Fetching pets for userId: ${this.userId}`);
        axios.get(`/api/pets/owner/${this.userId}`, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        .then(response => {
          console.log("Pets data received:", response.data);
          this.pets = response.data;
        })
        .catch(error => {
          console.error("获取宠物信息失败:", error);
        });
      } else {
        console.error("未能获取用户ID");
      }
    },
    formatDate(date) {
      if (date) {
        const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
        return new Date(date).toLocaleDateString(undefined, options);
      }
      return '';
    },
    deletePet(petId) {
      axios.delete(`/api/pets/delete/${petId}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      .then(response => {
        this.$message.success('宠物已删除');
        this.fetchPets(); // 重新获取宠物列表
      })
      .catch(error => {
        this.$message.error('删除失败，请重试');
        console.error("删除宠物失败:", error);
      });
    },
    editPet(pet) {
      this.$router.push({
        path: '/create-profile',
        query: { petId: pet.id }
      });
    },
    chatWithPet(petId) {
      this.$router.push({
        path: '/chat',
        query: { petId: petId }
      });
    },
    viewDiary(petId) {
      this.$router.push({
        path: '/diary',
        query: { petId: petId }
      });
    }
  }
};
</script>

<style scoped>
.container {
  position: relative;
  width: 100%;
  min-height: 100vh; /* 确保容器高度随内容变化 */
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 使内容从顶部开始对齐 */
  background-color: #000; /* 备用背景颜色 */
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/background.jpg'); /* 使用相对路径引入图片 */
  background-size: cover; /* 确保背景图片覆盖整个容器 */
  background-repeat: no-repeat;
  background-attachment: fixed; /* 背景图片随页面滚动 */
  background-position: center;
  opacity: 0.8; /* 根据需要调整透明度 */
}

.content {
  position: relative;
  z-index: 1;
  width: 100%;
  padding: 20px;
}

.view-profile {
  margin: 20px;
}

.pet-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9); /* 设置背景颜色和透明度 */
  border-radius: 8px; /* 设置圆角 */
}

.button-container {
  display: flex;
  flex-wrap: nowrap; /* 禁止换行 */
  justify-content: space-between; /* 按钮均匀分布 */
  margin-top: 10px;
}

.custom-button {
  flex: 1; /* 按钮均分父容器空间 */
  margin: 0 1px; /* 按钮之间的间距 */
  min-width: 50px; /* 设置按钮最小宽度 */
  max-width: 50px; /* 设置按钮最大宽度 */
  padding: 4px 0; /* 设置按钮的上下内边距 */
  text-align: center; /* 文字居中 */
}
</style>
